import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { EditorConfig } from './editor.config';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-editor',
  templateUrl: './editor.component.html',
  styleUrls: ['./editor.component.sass']
})

export class EditorComponent implements OnInit {
  conf = new EditorConfig(0);

  title: string;
  content: string;

  modalVisible = false;

  constructor(private message: NzMessageService, private http: HttpClient) { }

  ngOnInit() {
    this.conf.height = (document.documentElement.offsetHeight || document.body.offsetHeight) - 140 + '';
  }

  /**
   * 同步属性内容
   * @param str 内容
   */
  syncModel(str): void {
    this.content = str;
  }

  /**
   * 发布文章
   */
  publish(): void {
    if (!!!this.title || this.title.trim().length === 0) {
      this.message.create('error', '还差着主题呢!');
      return;
    }

    if (!!!this.content || this.content.trim().length === 0) {
      this.message.create('error', '一片空白也能叫文章?');
      return;
    }

    this.modalVisible = true;
  }

  modalCancel() {
    this.modalVisible = false;
  }

  modalSure() {
    this.modalVisible = false;

    this.http.post(`/api/ca/save`, {
      title: this.title,
      content: this.content
    }).subscribe(result => {
      if (result) {
        window.history.back();
      } else {
        this.message.create('error', '保存失败, 请稍候重试?');
      }
    });
  }
}
